package com.example.javawebdemo.servlets;

import com.example.javawebdemo.dao.DAOFactory;
import com.example.javawebdemo.dao.UserDAO;
import com.example.javawebdemo.models.User;
import com.example.javawebdemo.utils.PasswordUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少action参数");
            return;
        }

        try {
            switch (action) {
                case "login":
                    handleLogin(request, response);
                    break;
                case "register":
                    handleRegister(request, response);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的action类型");
            }
        } catch (SQLException e) {
            throw new ServletException("数据库操作异常", e);
        }
    }

    private void handleLogin(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserDAO userDAO = DAOFactory.getUserDAO();
        User user = userDAO.findByUsername(username);

        // [!] 修改验证方法 [!]
        if (user != null && PasswordUtils.checkPassword(password, user.getPassword())) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            response.sendRedirect("management-Index.jsp");
        } else {
            setErrorAndForward(request, response, "用户名或密码错误", "login.jsp");
        }

//        System.out.println(BCrypt.hashpw("12345678", BCrypt.gensalt()));

    }


    private void handleRegister(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setPassword(PasswordUtils.hashPassword(request.getParameter("password"))); // 密码哈希加密
        user.setEmail(request.getParameter("email"));
        user.setPhone(request.getParameter("phone"));

        UserDAO userDAO = DAOFactory.getUserDAO();
        if (userDAO.registerUser(user)) {
            response.sendRedirect("register-success.jsp");
        } else {
            setErrorAndForward(request, response, "注册失败，用户名已存在", "register.jsp");
        }
    }

    private void setErrorAndForward(HttpServletRequest request, HttpServletResponse response,
                                    String errorMessage, String forwardPage)
            throws ServletException, IOException {
        request.setAttribute("errorMessage", errorMessage);
        request.getRequestDispatcher(forwardPage).forward(request, response);
    }
}
